using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;

#if UNITY_EDITOR
using UnityEditor;
#endif

[ExecuteInEditMode()]
[AddComponentMenu("GK/Sequencer/EditorView/gkSequencerTrackEditorView")]
[RequireComponent(typeof(gkScreenTransform))]
/// \class  gkSequencerTrackEditorView
/// \brief 	The track view
public class gkSequencerTrackEditorView : MonoBehaviour
{
#if UNITY_EDITOR
	/// The track
	private gkSequencerTrack m_rTrack;
	
	/// The screen transform
	gkScreenTransform m_rScreenTransform;
	
	/// \brief  Call after the script load
	void Start()
	{
		// Get the track
		m_rTrack = GetComponent<gkSequencerTrack>();
			
		// Grab the screen transform
		m_rScreenTransform = GetComponent<gkScreenTransform>();
	}
	
	/// \brief  Called on sequencer GUI update
	public void DisplaySequencerGUI()
	{
		if(m_rTrack != null)
		{
			GUILayout.BeginHorizontal();
			{
				// Display the track inspector
				DisplayTrackLabel();
				
				// Display the zone where paste the action
				DisplayActionZone();
			}
			GUILayout.EndHorizontal();
			
			// Display the actions
			DisplayActions();
			
			// Handle the action drag and drop
			HandleDragAndDrop();
		}
	}
	
	/// \brief  Display track Inspector 
	void DisplayTrackLabel()
	{
		// Display the box
		GUILayout.Box("Track", "Track_Label");
	}
	
	/// \brief  Display track Inspector 
	void DisplayActionZone()
	{
		// Display the box
		GUILayout.Box("", "Track_ActionZone");
		
		// Update the screen transform of the action zone
		m_rScreenTransform.rectangleBounds = GUILayoutUtility.GetLastRect();
	}
	
	/// \brief  Display the actions GUI
	public void DisplayActions()
	{
		gkSequencerAction[] rActions;
			
		// Get the track actions
		rActions = GetComponentsInChildren<gkSequencerAction>();
		
		// Display all the track actions
		foreach(gkSequencerAction rAction in rActions)
		{
			rAction.SendMessage("DisplaySequencerGUI", SendMessageOptions.DontRequireReceiver);
		}
	}
	
	/// \brief  Handle the action drag and drop
	void HandleDragAndDrop()
	{
		// Handle drag and drop from an outside source:
		if (Event.current != null && (Event.current.type == EventType.DragUpdated || Event.current.type == EventType.DragPerform))
		{
			EventType eventType = Event.current.type;
			
			// Show a copy icon on the drag
			DragAndDrop.visualMode = DragAndDropVisualMode.Copy;

			if (eventType == EventType.DragPerform)
			{
				//Test adding component
				for (int i = 0; i < DragAndDrop.objectReferences.Length; ++i)
				{	
					Type type;
					
					type = Type.GetType(DragAndDrop.objectReferences[i].name);
					if(type != null && type.IsSubclassOf(typeof(gkSequencerAction)))
					{
						DragAndDrop.AcceptDrag();
						
						// Add the drop action
						AddAction(type.Name);
					}
				}
			}

			Event.current.Use();
		}
	}
	
	/// \brief  Add a new action
	void AddAction(string a_rActionName)
	{
		m_rTrack.AddAction(a_rActionName);
	}
#endif
}